636. 函数的独占时间

636. 函数的独占时间

Similar Question

leading to the advanced question

Solution Tips

方案一: 栈

/**
 * @param {number} n
 * @param {string[]} logs
 * @return {number[]}
 */
 class Stack {
  constructor() {
    this.items = []; // 使用数组存储数据
  }
  push(item) {
    this.items.push(item); // 往栈里压入一个元素
  }
  pop() {
    // 如果不为空
    if(!this.isEmpty()) return this.items.pop(); // 把栈顶的元素移除
  }
  top() {
    return this.items[this.items.length - 1]; // 返回栈顶的元素
  }
  isEmpty() {
    return this.items.length === 0; //返回栈是否为空
  }
  size() {
    return this.items.length; // 返回栈的大小
  }
  clear() {
    this.items = []; // 清空栈
  }
  toString(){
    return this.items.reduce(function(str,val){
      return str + val
    },'')
  }
}
var exclusiveTime = function(n, logs) {
    const len = logs.length
    const res = new Array(n).fill(0);
    const stack = new Stack();

    for(let i = 0; i < len; i++) {
        const log = logs[i].split(':')
        const [index, type, timestamp] = log
        if (type === 'start') {
            stack.push(log);
        }
        else {
            const start = stack.pop();
            const duration = timestamp - start[2] + 1;
            res[index] = (res[index] || 0) + duration
            // 只计算在栈顶的时间
            // 此时在栈顶的 log 需要减去 duration
            const top = stack.top();
            if (top) {
                const [j] = top
                res[j] = (res[j] || 0) - duration
            }
        }
    }

    return res;
};